#include "DCLinkList.h"

void InitDCList(DCList *list)
{
    InitDLlist(&list->dllist);
}

void InsertDCListTail(DCList *list, ElementType element)
{
    InsertDLlistTail(&list->dllist, element);
    list->dllist.tail->next = list->dllist.head->next;
    list->dllist.head->next->prev = list->dllist.tail;
}

void InsertDCListHead(DCList *list, ElementType element)
{
    InsertDCListTail(list, element);
    list->dllist.tail = list->dllist.tail->prev;
    list->dllist.head->next = list->dllist.tail->next;
}

void RemoveHead(DCList *list)
{
    if (list->dllist.len == 0)
    {
        printf("list empty, RemoveHead error!\n");
        return;
    }
    node *listHead = list->dllist.head->next;
    list->dllist.tail->next = listHead->next;
    if (listHead->next != NULL)
    {
        listHead->next->prev = list->dllist.tail;
    }
    list->dllist.head->next = listHead->next;
    free(listHead);
    list->dllist.len--;
}

ElementType *FindHead(DCList *list)
{
    if (list->dllist.len == 0)
    {
        return NULL;
    }
    return list->dllist.head->next->value;
}

bool InsertDCListByIndex(DCList *list, int index, ElementType element)
{
    if (index == 0)
    {
        node *newNode = CreateNode(element);
        newNode->next = list->dllist.head->next;
        list->dllist.head->next->prev = newNode;
        list->dllist.head->next = newNode;
        newNode->prev = list->dllist.head;
        list->dllist.tail->next = newNode;
    }
    else if (index == list->dllist.len)
    {
        node *newNode = CreateNode(element);
        newNode->next = list->dllist.tail->next;
        newNode->prev = list->dllist.tail;
        list->dllist.tail->next = newNode;
        list->dllist.tail = newNode;
    }
    else
    {
        InsertByIndex(&list->dllist, index, element);
    }
}

void TravelDCList(DCList *list)
{
    node *travel = list->dllist.head->next;
    while (travel != list->dllist.tail)
    {
        printf("%d ", (int)travel->value);
        travel = travel->next;
    }
    printf("%d ", (int)travel->value);
    printf("\n");
}
